<template>
  <div>
    <div>
      <input type="text" v-model="note" placeholder="输入备注" />
      <input type="number" v-model.number="hours" placeholder="时" />
      <input type="number" v-model.number="minutes" placeholder="分" />
      <input type="number" v-model.number="seconds" placeholder="秒" />
      <button @click="addCountdown">添加倒计时</button>
    </div>

    <ul>
      <li v-for="(countdown, index) in countdowns" :key="countdown.id" @click="checkAndRemoveCountdown(index)">
        <div v-if="countdown.timeLeft > 0">
          {{ countdown.note }} 剩余时间：{{ formatTime(countdown.timeLeft) }}
          <span class="close" @click.stop="removeCountdown(index)">×</span>
        </div>
        <div v-else>
          {{ countdown.note }} 时间到！
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const note = ref('');
    const hours = ref(0);
    const minutes = ref(0);
    const seconds = ref(0);
    const countdowns = ref([]);

    const addCountdown = () => {
      const totalSeconds = hours.value * 3600 + minutes.value * 60 + seconds.value;
      const countdown = {
        id: Date.now(),
        note: note.value,
        timeLeft: totalSeconds,
      };

      const intervalId = setInterval(() => {
        if (countdown.timeLeft > 0) {
          countdown.timeLeft--;
          countdowns.value = [...countdowns.value];
        } else {
          clearInterval(intervalId);
          playBeepSound();
        }
      }, 1000);

      countdowns.value.push(countdown);

      // 重置输入
      note.value = '';
      hours.value = 0;
      minutes.value = 0;
      seconds.value = 0;
    };

    const removeCountdown = (index) => {
      countdowns.value.splice(index, 1);
    };

    const checkAndRemoveCountdown = (index) => {
      if (countdowns.value[index].timeLeft <= 0) {
        removeCountdown(index);
      }
    };

    const formatTime = (time) => {
      const h = Math.floor(time / 3600);
      const m = Math.floor((time % 3600) / 60);
      const s = time % 60;
      return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
    };

    const playBeepSound = () => {
      const audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const oscillator = audioContext.createOscillator();
      oscillator.type = 'square';
      oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
      oscillator.connect(audioContext.destination);
      oscillator.start();
      oscillator.stop(audioContext.currentTime + 0.2);
    };

    return {
      note,
      hours,
      minutes,
      seconds,
      countdowns,
      addCountdown,
      removeCountdown,
      checkAndRemoveCountdown,
      formatTime,
    };
  },
};
</script>

<style>
.close {
  cursor: pointer;
  padding: 0 5px;
}
</style>
